<?php

/**
 * @author chenxuezhi
 * @copyright 2016
 */

namespace Zxgame\Controller;
use Common\Controller\ApiController;

class IndexController extends ApiController {
    
    // 未授权登陆
    public function loginNotAuth()
    {
        $userid = I('userid','','string'); // 用户userid
        if(!$userid){
            $userid = uuid('Xx');
            $dateline = date('Y-m-d H:i:s');
            $ret = M('users')->add(array(
                'userid'=>$userid,
                'nickname'=>'',
                'avatar'=>'',
                'gold'=>0,
                'create_time'=>$dateline
            ));

            if($ret){
                $users['userid'] = $userid;
                $users['nickname'] = '';
                $users['avatar'] = '';
                $users['gold'] = 0;
                $users['create_time'] = $dateline;
                
                $jsons['errno'] = 0;
                $jsons['result'] = $users;
                $this->ajaxReturn($jsons);
            }else{
                $jsons['errno'] = 1;
                $jsons['msg'] = '操作失败';
                $this->ajaxReturn($jsons);
            }
        }else{
            $users = M('users')->where("userid = '$userid'")->find();
            if($users){
                // 授权登录
                if(!empty($users['nickname']) && !empty($users['avatar'])){
                    $types = 4;
                }else{
                    $types = 3;
                }
                $data['types'] = $types;
                M('users')->where("userid = '$userid'")->save($data);
                $jsons['errno'] = 0;
                $jsons['result'] = $users;
                $this->ajaxReturn($jsons);
            }else{
                //$userid = uuid('Xx');
                $dateline = date('Y-m-d H:i:s');
                $ret = M('users')->add(array(
                    'userid'=>$userid,
                    'nickname'=>'',
                    'avatar'=>'',
                    'gold'=>0,
                    'create_time'=>$dateline,
                    'types'=>1
                ));
                
                if($ret){
                    $users['userid'] = $userid;
                    $users['nickname'] = '';
                    $users['avatar'] = '';
                    $users['gold'] = 0;
                    $users['create_time'] = $dateline;
                    
                    $jsons['errno'] = 0;
                    $jsons['result'] = $users;
                    $this->ajaxReturn($jsons);
                }else{
                    $jsons['errno'] = 1;
                    $jsons['msg'] = '操作失败';
                    $this->ajaxReturn($jsons);
                }
            }
        }
    } 
    
    // 登陆接口
    public function login()
    {
        $appId = C('APPID');
        $appSecret = C('APPSECRET');
        $code = I('code','','string');
        
        $nickname = I('nickname','','string');
        $avatar = I('avatar','','string');

        if(!$code){
            $jsons['errno'] = 1;
            $jsons['msg'] = 'code不能为空';
            $this->ajaxReturn($jsons);
        }else if(empty($nickname)){
            $jsons['errno'] = 2;
            $jsons['msg'] = '昵称不能为空';
            $this->ajaxReturn($jsons);
        }else if(empty($avatar)){
            $jsons['errno'] = 3;
            $jsons['msg'] = '头像不能为空';
            $this->ajaxReturn($jsons);
        }
        
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appSecret&js_code=$code&grant_type=authorization_code";
        
        $opts['http'] = array('method'=>'GET', 'timeout'=>5); // 设置超时5s
        $data = @file_get_contents($url, false, stream_context_create($opts)); 
        
        //$lastSql = '';
        $json2arr = $data ? @json_decode($data, true) : '';
        if(empty($json2arr['errcode'])) {
            $json = json_decode($data, true);
            
            $userId = isset($json['openid']) ? $json['openid'] : '';
            
            $map['userid'] = $userId;
            if(!$users = M('users')->where($map)->find()){
                $dateline = date('Y-m-d H:i:s');
                $ret = M('users')->add(array(
                    'userid'=>$userId,
                    'nickname'=>$nickname,
                    'draw_number'=>1,
                    'upgrade_state'=>0,
                    'avatar'=>$avatar,
                    'create_time'=>$dateline,
                    'types'=>3
                ));
                
                if($ret){
                    $users['guide'] = true;
                    $users['userid'] = $userId;
                    $users['nickname'] = $nickname;
                    $users['draw_number'] = 1;
                    $users['avatar'] = $avatar;
                    $users['upgrade_state'] = 0;
                    $users['create_time'] = $dateline;
                }
            // 更改则更新用户信息    
            }else if($users['nickname'] != $nickname || $users['avatar'] != $avatar){
                M('users')->where($map)->save(array(
                    'nickname'=>$nickname,
                    'avatar'=>$avatar
                ));
            }
            
            // 如果用户存在则合并
            if($users){
                $data = array_merge($json2arr, $users); // 合并数组   
            }
            
            // 返回用户最优成绩
            $ret = M('users_game_result')->where($map)->order('score desc')->find();
            $data['good_score'] = !empty($ret['score']) ? $ret['score'] : 0;
            
            // 返回用户最优成绩(无尽模式）
            $ret = M('users_game_result_other')->where($map)->order('score desc')->find();
            $data['good_score2'] = !empty($ret['score']) ? $ret['score'] : 0;
            //$lastSql = M()->getLastSql();
  
        }
        
        //$data['lastSql'] = $lastSql;
        $this->ajaxReturn($data);
    }
    
    // 解密数据
    public function cryptData()
    {
        $appid = C('APPID'); // Appid
        $sessionKey = I('sessionKey','','string'); // sessionKey
        $encryptedData = I('encryptedData','','string'); // 加密数据
        $iv = I('iv','','string');
        $userid = I('userid','','string'); // 用户userid

        $pc = new \Org\Util\WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        
        $data = $data ? json_decode($data, true) : '';
        $openGId = isset($data['openGId']) ? $data['openGId'] : 0;
        
        $strat_time = date('Y-m-d 00:00:00'); // 今天开始时间
        $end_time = date('Y-m-d 23:59:59'); // 今天结束日期
        $map['userid'] = $userid;
        $map['gid'] = $openGId;
        $map['create_time'] = array('BETWEEN', array($strat_time,$end_time));
        $shareCount = M('share_group_log')->where($map)->count(1);
        if(empty($userid)){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }else if($shareCount > 0){
            $jsons['errno'] = 2;
            $jsons['msg'] = '每日同一群只能分享一次';
            $this->ajaxReturn($jsons);
        }else if ($errCode == 0) {
            
            $data['shareState'] = false;
            // 群分享记录
            $groups['userid'] = $userid;
            $groups['gid'] = $openGId;
            $groups['create_time'] = date('Y-m-d H:i:s');
            if($ret = M('share_group_log')->add($groups)){
                $data['shareState'] = true;
            }
            
            $jsons['errno'] = 0;
            $jsons['msg'] = '成功解密';
            $jsons['result'] = $data;
            $this->ajaxReturn($jsons);
        } else {
            $jsons['errno'] = $errCode;
            $jsons['msg'] = '解密失败';
            $this->ajaxReturn($jsons);
        }
    }
    
    // 排行榜
    public function rankingList()
    {
        $users = I('users','','string');
        $page = I('page',1,'int'); // 页码
        $pageNum = I('pageNum',20,'int'); // 每页数量
        $type  = I('type',1,'int'); // 1好友排行，2世界排行
        $gameMode = I('gameMode',1,'int');
        $offset = ($page - 1) * $pageNum;

        $ret = array();
        if($type == 2){
            // $model = ($gameMode == 1) ? M('users_game_result') : M('users_game_result_other');
            // $ret = $model->field('userid,nickname,avatar,game_mode,MAX(score) AS s')
            //     ->where(array('game_mode'=>$gameMode))
            //     ->group('userid')
            //     ->order('s desc')
            //     ->limit($offset,$pageNum)
            //     ->select();
            
            $field1 = 'userid,nickname,avatar,score as s';
            $field2 = 'userid,nickname,avatar,grade as s';
            
            $field = $gameMode == 1 ? $field1 : $field2;
            $where['black_list'] = 1;
            $ret = M('users')->field($field)->where($where)->order('s desc')->limit(200)->select();

        }else{
            $jsons['errno'] = 2;
            $jsons['msg'] = '排序类型不正确';
            $this->ajaxReturn($jsons);
        }
        
        $jsons['errno'] = 0;
        $jsons['result'] = $ret;
        $this->ajaxReturn($jsons);
    }
    
    // 检查用户排行变化
    public function rankingChange()
    {
        $userid = I('userid','','string');
        $game_mode = I('game_mode',1,'int');
        $limit = 200;
      
        if(!$userid){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }else{
            $map['userid'] = $userid;
            $model = ($game_mode == 1) ? M('users_game_result') : M('users_game_result_other');

            $res = $model->where($map)->order('id desc')->limit(1)->select();

            if(empty($res)) {
                $jsons['errno'] = 0;
                $jsons['result'] = $res;
                $this->ajaxReturn($jsons);
            }

            $ret = $model->field('max(score) as score,userid,id,nickname,avatar')
                ->group('userid')
                ->order('score desc,id asc')
                ->limit($limit)
                ->select();

            $rankNum = 0;
            if(!empty($ret)) {
                foreach($ret as $k=>$v) {
                   
                    if($userid == $v['userid'] && $res[0]['score'] >= $v['score']) {
                        $rankNum = $k+1;
                        break;
                    }
                    
                    if($res[0]['score'] > $v['score']) {
                        $rankNum = $k+1;
                        break;
                    }
                }
            }
            if($rankNum==0) {
                $rankNum = count($ret) + 1 ;
            }
    
            $res[0]['rankNum'] = $rankNum;
            
            $jsons['errno'] = 0;
            $jsons['result'] = $res;
            $this->ajaxReturn($jsons);  
        }

    }
    
    // 游戏复活
    public function revive()
    {
        $userid = I('userid','','string'); // 用户userid
        $gold = I('gold',0,'int'); // 复活金币
        
        $map['userid'] = $userid; 
        if(!$userid){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
        }else if(empty($gold)){
            $jsons['errno'] = 2;
            $jsons['msg'] = '复活金币不能为空';
        }else if(!$users = M('users')->where($map)->find()){
            $jsons['errno'] = 3;
            $jsons['msg'] = '用户不存在';
        }else if($users['gold'] < $gold){
            $jsons['errno'] = 4;
            $jsons['msg'] = '金币不足';
        }else{
            $ret = M('users')->where($map)->setDec('gold',$gold);
            
            if($ret){
                $jsons['errno'] = 0;
                $jsons['msg'] = '操作成功';
            }else{
                $jsons['errno'] = 5;
                $jsons['msg'] = '操作失败';
            }
        }
        $this->ajaxReturn($jsons);   
    }
    
    // 抽奖
    public function draw()
    {
        $userid = I('userid','','string'); // 用户userid
        $strat_time = date('Y-m-d 00:00:00'); // 今天开始时间
        $end_time = date('Y-m-d 23:59:59'); // 今天结束日期

        $users = M('users')->where("userid = '$userid'")->find();
        if($users && $users['draw_number'] > 0){
            
            // 今日抽奖奖品
            $map['userid'] = $userid;
            $map['create_time'] = array('BETWEEN', array($strat_time, $end_time));
            $myDraws = M('users_draw_log')->where($map)->getField('reward_grid,reward_name');
            
            // 去除已中奖过的
            $list = array(1=>25, 2=>25, 3=>25, 4=>10, 5=>5, 6=>10);
            foreach($myDraws as $k=>$v){
                if(isset($list[$k])){
                    $list[$k] = 0;
                }
            }
            $sum = array_sum($list);
            
            if($sum){ 
                // 随机抽奖
                $randNum = mt_rand(1, $sum);
                $id = 0;
                foreach ($list as $k => $v) {
                    if ($randNum <= $v) {
                        $id = $k;
                        break;
                    }
                    $randNum -= $v;
                }
                
                $drawList = C('GAME_DRAW');
                $drawRet = $drawList[$id];
                
                $model = M();
                $model->startTrans();
                
                // 记录抽奖日志
                $data['userid'] = $userid;
                $data['reward_type'] = $drawRet['type'];
                $data['reward_grid'] = $drawRet['grid'];
                $data['reward_name'] = $drawRet['name'];
                $data['create_time'] = date('Y-m-d H:i:s');
                $ret1 = M('users_draw_log')->add($data);

                // 更新用户抽奖次数
                if($drawRet['type'] == 1){
                    $fields['draw_number'] = array('exp','draw_number - 1');
                    $fields['gold'] = array('exp',"gold + {$drawRet['id']}");  
                    $ret2 = M('users')->where("userid = '$userid'")->save($fields);
                    $ret3 = true;
                }else{
                    $ret2 = M('users')->where("userid = '$userid'")->setDec('draw_number',1);
                    
                    $equips['userid'] = $userid;
                    $equips['equip_id'] = $drawRet['id'];
                    $equips['equip_name'] = $drawRet['name'];
                    $equips['num'] = 1;
                    $equips['create_time'] = date('Y-m-d H:i:s');
                    $ret3 = M('users_equip')->add($equips);
                }
                
                if($ret1 && $ret2 && $ret3){
                    $model->commit();
                    
                    $jsons['errno'] = 0;
                    $jsons['msg'] = '抽奖结果';
                    $jsons['result'] = $drawRet;
                    $this->ajaxReturn($jsons);
                }else{
                    $model->rollback();
                    
                    $jsons['errno'] = 1;
                    $jsons['msg'] = '抽奖失败';
                    $this->ajaxReturn($jsons);
                }
            }else{
                $jsons['errno'] = 2;
                $jsons['msg'] = '奖品已抽空';
                $this->ajaxReturn($jsons);
            }
        }else{
            $jsons['errno'] = 3;
            $jsons['msg'] = '抽奖次数不足';
            $this->ajaxReturn($jsons);
        }
    }
    
    // 升级角色
    public function upgradeRole()
    {
        $userid = I('userid','','string');
        $gold = 1666; // 升级金币
        
        if(!$users = M('users')->where("userid = '$userid'")->find()){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户不存在';
            $this->ajaxReturn($jsons);
        }else if($users['gold'] < $gold){
            $jsons['errno'] = 2;
            $jsons['msg'] = '金币不足';
            $this->ajaxReturn($jsons);
        }else{
            
            // 获取用户可升级装备
            $equip_ids = array();
            $equips = C('GAME_EQUIP');
            foreach($equips as $items){
                if($items['upgrade'] == 1){
                    $equip_ids[] = $items['id'];    
                }
            }
            
            $map['userid'] = $userid;
            $map['equip_id'] = array('in',$equip_ids);
            $count = M('users_equip')->where($map)->count();
            
            if($count < 6){
                $jsons['errno'] = 3;
                $jsons['msg'] = '装备不足';
                $this->ajaxReturn($jsons);
            }
            
            $map['userid'] = $userid;
            $map['upgrade_state'] = 0;
            
            $data['upgrade_state'] = 1;
            $data['gold'] = array('exp',"gold - $gold");
            $ret = M('users')->where($map)->setField($data);
            if($ret){
                $jsons['errno'] = 0;
                $jsons['msg'] = '升级成功';
            }else{
                $jsons['errno'] = 4;
                $jsons['msg'] = '升级失败';
            }
            $this->ajaxReturn($jsons);
        }
    }
    
    
    // 获取用户装备
    public function getUserEquip()
    {
        $userid = I('userid','','string');
        $page = I('page',1,'int'); // 页码
        $pageNum = I('pageNum',20,'int'); // 每页数量
        $gamEquips = C('GAME_EQUIP');
        
        $offset = ($page - 1) * $pageNum;
        
        $map['userid'] = $userid;
        $equipList = M('users_equip')
            ->where($map)
            ->limit($offset, $pageNum)
            ->select();
            
        // 遍历配置属性
        foreach($equipList as &$items){
            if(isset($gamEquips[$items['equip_id']])){
                $items['level'] = $gamEquips[$items['equip_id']]['level'];
                $items['upgrade'] = $gamEquips[$items['equip_id']]['upgrade'];
                $items['group'] = $gamEquips[$items['equip_id']]['group'];
            }
        }

        $jsons['errno'] = 0;
        $jsons['result'] = $equipList;
        $this->ajaxReturn($jsons);
    }
    
    // 金币购买抽奖次数
    public function buyDrawNum()
    {
        $userid = I('userid','','string'); // 用户userid
        $buyerNum = 1; // 购买次数
        $gold = 10; // 扣除金币
        $strat_time = date('Y-m-d 00:00:00'); // 今天开始时间
        $end_time = date('Y-m-d 23:59:59'); // 今天结束日期
        
        $map['userid'] = $userid;
        $map['type'] = 1; // 购买抽奖次数
        $map['create_time'] = array('BETWEEN', array($strat_time,$end_time));
        $count = M('users_gold_log')->where($map)->count(1);
        if($count < $buyerNum){
            if(!$users = M('users')->where("userid = '$userid'")->find()){
                $jsons['errno'] = 1;
                $jsons['msg'] = '用户不存在';
                $this->ajaxReturn($jsons);
            }else if(isset($users['gold']) && $users['gold'] < $gold){
                $jsons['errno'] = 2;
                $jsons['msg'] = '金币不足';
                $this->ajaxReturn($jsons);
            }else{
                // 扣除金币，增加抽奖次数
                $data = array(
                    'gold'=>array('exp',"gold - $gold"), // 扣除用户金币
                    'draw_number'=>array('exp',"draw_number + 1"), // 增加抽奖次数
                );
                $ret1 = M('users')->where("userid = '$userid'")->save($data); 
                
                // 记录购买日志
                $ret2 = M('users_gold_log')->add(array(
                    'userid'=>$userid,
                    'type'=>1, // 购买抽奖
                    'gold'=>-$gold,
                    'balance'=>$users['gold'],
                    'remark'=>'购买抽奖次数',
                    'create_time'=>date('Y-m-d H:i:s')
                )); 
                
                $model = M();
                $model->startTrans();
                
                if($ret1 && $ret2){
                    $model->commit();
                    
                    $jsons['errno'] = 0;
                    $jsons['msg'] = '购买成功';
                    $this->ajaxReturn($jsons);
                }else{
                    $model->rollback();
                    
                    $jsons['errno'] = 3;
                    $jsons['msg'] = '购买失败';
                    $this->ajaxReturn($jsons);
                }           
            }
        }else{
            $jsons['errno'] = 1;
            $jsons['msg'] = '你已购买过，请勿重复操作';
            $this->ajaxReturn($jsons);
        }
    }
    
    // 分享奖励抽奖次数
    public function shareAward()
    {
        $userid = I('userid','','string'); // 用户userid
        $shareNum = 1; // 每天分享次数
        $strat_time = date('Y-m-d 00:00:00'); // 今天开始时间
        $end_time = date('Y-m-d 23:59:59'); // 今天结束日期
        
        $map1['userid'] = $userid;
        $map1['create_time'] = array('BETWEEN', array($strat_time,$end_time));
        $shareCount = M('users_share_log')->where($map1)->count(1);
        
        if($shareCount < $shareNum){
            $model = M();
            $model->startTrans();
            
            // 增加抽奖次数
            $ret1 = M('users')->where("userid = '$userid'")->setInc('draw_number',1);
            
            // 分享记录
            $data['userid'] = $userid;
            $data['share_type'] = 0;
            $data['create_time'] = date('Y-m-d H:i:s');
            $ret2 = M('users_share_log')->add($data);
            
            if($ret1 && $ret2){
                $model->commit();
                
                $jsons['errno'] = 0;
                $jsons['msg'] = '分享成功';
                $this->ajaxReturn($jsons);
            }else{
                $model->rollback();
                
                $jsons['errno'] = 2;
                $jsons['msg'] = '分享失败';
                $this->ajaxReturn($jsons);
            }
        }else{
            $jsons['errno'] = 1;
            $jsons['msg'] = '你已分享过，请勿重复操作';
            $this->ajaxReturn($jsons);
        }
    }
    
    // 获取用户信息
    public function getUserInfo(){
        $userid = I('userid','','string');
        
        if(!$userid){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }
        
        $map['userid'] = $userid;
        $users = M('users')->where($map)->find();
        if($users){
            
            // 用户最优成绩
            $ret = M('users_game_result')->where($map)->order('score desc')->find();
            $users['good_score'] = !empty($ret['score']) ? $ret['score'] : 0;
            
            // 用户最优成绩(无尽模式）
            $ret = M('users_game_result_other')->where($map)->order('score desc')->find();
            $users['good_score2'] = !empty($ret['score']) ? $ret['score'] : 0;
            
            $jsons['errno'] = 0;
            $jsons['result'] = $users;            
        }else{
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户不存在';
        }

        $this->ajaxReturn($jsons);
    }
    
    // 添加装备
    public function addEquip()
    {
        $userid = I('userid','','string');
        $equipId = I('equipId','','int');
        $equipList = C('GAME_EQUIP');
        
        if(!$userid){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }else if(!isset($equipList[$equipId])){
            $jsons['errno'] = 2;
            $jsons['msg'] = '装备不存在';
            $this->ajaxReturn($jsons);
        }else{
            $map['userid'] = $userid;
            $map['equip_id'] = $equipId;
            
            if(M('users_equip')->where($map)->find()){
                $ret = M('users_equip')->where($map)->setInc('num',1);
                if($ret){
                    $jsons['errno'] = 0;
                    $jsons['msg'] = '更新成功';  
                }else{
                    $jsons['errno'] = 1;
                    $jsons['msg'] = '更新失败';
                }
                $this->ajaxReturn($jsons);    
            }else{
                $data['userid'] = $userid;
                $data['equip_id'] = $equipId;
                $data['equip_name'] = $equipList[$equipId]['name'];
                $data['num'] = 1; // 装备数量
                $data['create_time'] = date('Y-m-d H:i:s');
                
                $ret = M('users_equip')->add($data);
                if($ret){
                    $jsons['errno'] = 0;
                    $jsons['msg'] = '增加成功';  
                }else{
                    $jsons['errno'] = 1;
                    $jsons['msg'] = '增加失败';
                }
                $this->ajaxReturn($jsons);                 
            }
        }

    }
    
    // 设置金币
    public function setGold()
    {
        $userid = I('userid','','string'); // 用户userid
        $type = I('type','inc','string'); // 操作类型：inc增加，dec减少
        $gold = I('gold',0,'int'); // 金币
        
        $map['userid'] = $userid;
        
        if(!$userid){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }else if(!$users = M('users')->where($map)->find()){
            $jsons['errno'] = 2;
            $jsons['msg'] = '用户不存在';
            $this->ajaxReturn($jsons);
        }else if($gold < 0){
            $jsons['errno'] = 3;
            $jsons['msg'] = '金币不能小于0';
            $this->ajaxReturn($jsons);
        }else if($type == 'dec' && $users['gold'] < $gold){
            $jsons['errno'] = 4;
            $jsons['msg'] = '金币不足';
            $this->ajaxReturn($jsons);
        }else if($type == 'dec'){ // 减少
            $ret = M('users')->where($map)->setDec('gold', $gold);
            if($ret){
                $jsons['errno'] = 0;
                $jsons['msg'] = '扣减成功';
            }else{
                $jsons['errno'] = 5;
                $jsons['msg'] = '扣减失败';
            }
            $this->ajaxReturn($jsons);
        }else if($type == 'inc'){ // 增加
            $ret = M('users')->where($map)->setInc('gold', $gold);
            if($ret){
                $jsons['errno'] = 0;
                $jsons['msg'] = '增加成功';  
            }else{
                $jsons['errno'] = 6;
                $jsons['msg'] = '增加失败';
            }
            $this->ajaxReturn($jsons);
        }else{
            $jsons['errno'] = 7;
            $jsons['msg'] = '操作类型不正确';
            $this->ajaxReturn($jsons);
        }
    }
    
    // 获取SessionKey
    public function getSessionKey()
    {
        $appId = C('APPID');
        $appSecret = C('APPSECRET');
        $code = I('code','','string');
                        
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appSecret&js_code=$code&grant_type=authorization_code";
        $opts['http'] = array('method'=>'GET', 'timeout'=>5); // 设置超时5s
        $data = @file_get_contents($url, false, stream_context_create($opts)); 
        
        $data = $data ? @json_decode($data, true) : '';
        $jsons['errno'] = 0;
        $jsons['result'] = $data;
        $this->ajaxReturn($jsons);
    }
    
    // 获取抽奖列表
    public function getDrawList()
    {
        $userid = I('userid','','string');
        $strat_time = date('Y-m-d 00:00:00'); // 今天开始时间
        $end_time = date('Y-m-d 23:59:59'); // 今天结束日期
        
        // 今日分享次数
        $map1['userid'] = $userid;
        $map1['create_time'] = array('BETWEEN', array($strat_time,$end_time));
        $data['shareCount'] = M('users_share_log')->where($map1)->count(1);
        
        // 今日购买次数
        $map2['userid'] = $userid;
        $map2['type'] = 1;
        $map2['create_time'] = array('BETWEEN', array($strat_time,$end_time));
        $data['buyerCount'] = M('users_gold_log')->where($map2)->count(1);
        
        // 今日可用抽奖次数，并初始化抽奖次数
        $users = M('users')->where("userid = '$userid'")->find();
        $curDate = date('Ymd');
        if($users && $users['draw_update'] < $curDate){
            M('users')->where("userid = '$userid'")->save(array('draw_update'=>$curDate,'draw_number'=>1));
            $data['drawCount'] = 1;
        }else{
            $data['drawCount'] = isset($users['draw_number']) ? $users['draw_number'] : 0; 
        }

        // 今日抽奖奖品
        $map3['userid'] = $userid;
        $map3['create_time'] = array('BETWEEN', array($strat_time,$end_time));
        $drawList = M('users_draw_log')->where($map3)->getField('reward_grid,reward_name');
        
        // 把用户已抽中的奖品状态标为true
        $data['awardList'] = C('GAME_DRAW');
        foreach($data['awardList'] as &$items){
            if(isset($drawList[$items['grid']])){
                $items['state'] = true;
            }
        }
        
        $jsons['errno'] = 0;
        $jsons['result'] = $data;
        $this->ajaxReturn($jsons);
    }
    
    // 获取用户邀请
    public function getUserInvite()
    {
        $userid = I('userid','','string'); 
        $start_time = date('Y-m-d 00:00:00'); // 开始时间
        $end_time = date('Y-m-d 23:59:59'); // 结束时间
        
        $map['I.userid'] = $userid;
        $map['I.create_time'] = array('BETWEEN',array($start_time, $end_time));
        $inviteList = M('users_invite')->alias('I')
            ->field('U.userid, U.nickname, U.avatar, I.invited_userid, I.create_time')
            ->join('INNER JOIN c_users U ON U.userid = I.invited_userid') 
            ->limit(4)
            ->order('I.id asc')
            ->where($map)
            ->select();
          
        $map1['userid'] = $userid;
        $map1['create_time'] = array('BETWEEN',array($start_time, $end_time));
        $inviteLog = M('users_invite_award_log')->where($map1)->getField('invited_userid,gold');
        
        if($inviteList){
            foreach($inviteList as &$items){
                if(isset($inviteLog[$items['invited_userid']])){
                    $items['state'] = 1;
                }else{
                    $items['state'] = 0;
                }
            }
        }
           
        $jsons['errno'] = 0;
        $jsons['result'] = $inviteList;
        $this->ajaxReturn($jsons);
    }
    
    // 领取邀请奖励
    public function getInviteAward()
    {
        $userid = I('userid','','string');
        $invited_userid = I('invited_userid','','string');
        $gold = I('gold',0,'int');
        
        $start_time = date('Y-m-d 00:00:00'); // 开始时间
        $end_time = date('Y-m-d 23:59:59'); // 结束时间
        
        $map['userid'] = $userid;
        $map['invited_userid'] = $invited_userid;
        $map['create_time'] = array('BETWEEN',array($start_time, $end_time));
        
        if($ret = M('users_invite_award_log')->where($map)->find()){
            $jsons['errno'] = 1;
            $jsons['msg'] = '你已领取过，请勿重复操作';
            $this->ajaxReturn($jsons);
        }else if(!$ret = M('users_invite')->where($map)->find()){ 
            $jsons['errno'] = 2;
            $jsons['msg'] = '非邀请用户，无权领取';
            $this->ajaxReturn($jsons);
        }else if($gold == 0 || $gold < 0){
            $jsons['errno'] = 3;
            $jsons['msg'] = '金币不能等于或小于0';
            $this->ajaxReturn($jsons);
        }else{
            
            $model = M();
            $model->startTrans();
            
            // 记录日志
            $data['userid'] = $userid;
            $data['invited_userid'] = $invited_userid;
            $data['gold'] = $gold;
            $data['create_time'] = date('Y-m-d H:i:s');
            $ret1 = M('users_invite_award_log')->add($data);
            
            // 增加金币
            $ret2 = M('users')->where("userid = '$userid'")->setInc('gold',$gold);
            
            if($ret1 && $ret2){
                $model->commit();
                
                $jsons['errno'] = 0;
                $jsons['msg'] = '操作成功';
                $this->ajaxReturn($jsons);
            }else{
                $model->rollback();
                
                $jsons['errno'] = 4;
                $jsons['msg'] = '操作失败';
            }
            
        }
    }

    // 邀请记录
    public function inviteRecord()
    {
        $userid = I('userid','','string');
        $invited_userid = I('invited_userid','','string');
        $start_time = date('Y-m-d 00:00:00'); // 开始时间
        $end_time = date('Y-m-d 23:59:59'); // 结束时间
        
        $map['userid'] = $userid;
        $map['invited_userid'] = $invited_userid;
        $map['create_time'] = array('BETWEEN',array($start_time, $end_time));
        
        
        if(empty($invited_userid) || $invited_userid == 'undefined'){
            $jsons['errno'] = 1;
            $jsons['msg'] = '被邀请人userid不能为空';
            $this->ajaxReturn($jsons);
        }else if($userid == $invited_userid){
            $jsons['errno'] = 2;
            $jsons['msg'] = '不能邀请自己';
            $this->ajaxReturn($jsons);
        }else if($ret = M('users_invite')->where($map)->find()){ 
            $jsons['errno'] = 3;
            $jsons['msg'] = '已被邀请过';
            $this->ajaxReturn($jsons);
        }else{
            $data['userid'] = $userid;
            $data['invited_userid'] = $invited_userid;
            $data['create_time'] = date('Y-m-d H:i:s');
            $ret = M('users_invite')->add($data);
            if($ret){
                $jsons['errno'] = 0;
                $jsons['msg'] = '邀请成功';
                $this->ajaxReturn($jsons);
            }else{
                $jsons['errno'] = 4;
                $jsons['msg'] = '邀请失败';
                $this->ajaxReturn($jsons);
            }
        }
    }

    // 记录游戏成绩
    public function addGameResult()
    {
        $userid = I('userid','','string');
        $score = I('score',0,'int');
        $nickname = I('nickname','','string');
        $avatar = I('avatar','','string');
        $gameMode = I('gameMode',1,'int');

        if(strlen($userid) == 30){
            $jsons['errno'] = 1;
            $jsons['msg'] = '游客不记录成绩';
            $this->ajaxReturn($jsons);
        }else if($userid == 'undefined' || $nickname == 'undefined' || $avatar == 'undefined'){
            $jsons['errno'] = 2;
            $jsons['msg'] = '字段不能为undefined';
            $this->ajaxReturn($jsons);
        }else if(!$userid){
            $jsons['errno'] = 3;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }else{
            
            $data['userid'] = $userid;
            $data['score'] = $score;
            $data['nickname'] = $nickname;
            $data['avatar'] = $avatar;
            $data['game_mode'] = $gameMode;
            $data['create_time'] = date('Y-m-d H:i:s');

            $map['userid'] = $userid;
            $userInfo = M('users')->where($map)->find();



            if($score > $userInfo['score']) {
                if($gameMode == 1) {
                    $param['score'] = $score;   
                }else {
                    $param['grade'] = $score;
                }
                M('users')->where($map)->save($param);
            }
        
            $model = ($gameMode == 1) ? M('users_game_result') : M('users_game_result_other');
        
            if($ret = $model->add($data)){
                $jsons['errno'] = 0;
                $jsons['msg'] = '添加成功';
                $this->ajaxReturn($jsons);
            }else{
                $jsons['errno'] = 4;
                $jsons['msg'] = '添加失败';
                $this->ajaxReturn($jsons);
            }               
        }
    }
    
    // 向房间推送消息
    public function pushMsg()
    {
        $roomId = I('roomId',0,'int');
        $state = I('state',1,'int'); // 1好友加入, 2开始游戏, 3放弃游戏, 4同步游戏界面
        $msg = I('msg','','string');
        $plus = I('plus','','string');

        $contents['roomId'] = $roomId;
        $contents['state'] = $state;
        $contents['msg'] = $msg;
        $contents['plus'] = $plus;
        $sendMsg = $this->sendMsg($contents);
        $sendMsg = str_replace("\n",'',$sendMsg);
        $jsons['state'] = $sendMsg;
        $this->ajaxReturn($jsons);
    }
    
    // Socket发送数据
    private function sendMsg($contents)
    {
        // 建立socket连接到内部推送端口
        $client = stream_socket_client('tcp://127.0.0.1:4321', $errno, $errmsg, 1);
        // 推送的数据，包含uid字段，表示是给这个uid推送
        
        // 发送数据，注意5678端口是Text协议的端口，Text协议需要在数据末尾加上换行符
        fwrite($client, json_encode($contents)."\n");
        // 读取推送结果
        return fread($client, 8192);   
    }

    // 获取服务器当前时间
    public function getServerTime(){
        $time = time();
        $this->response(0, "ok",$time);
    }

}